<?php
class FollowsController extends AppController{
	public $uses = array("User","Follow","Tweet","Timeline");

	private $numberPerPage = 20;
	/**
	 * list all follower of user
	 * @userid id of user want to get follower
	 * @accesstoken token of current logged in user
	 */
	public function followers(){
		if($this->request->is("post")){
			if(empty($this->request->data["get_userid"])){
				$data = array("status_code" => -1 , "message" => "access denied","entity" => array());
				return json_encode($data);
			}else{
				$userid = $this->request->data["get_userid"];
			}
				
			$current = $this->request->data["userid"];

			if(empty($this->request->data["paging"])){

				$this->Follow->unbindModel(array("belongsTo" => array("FollowerUser")));

				$followers = $this->Follow->find("all" , array("conditions" => array("following_id" => $userid),
						"fields" => array("FollowingUser.id","FollowingUser.username","FollowingUser.email","FollowingUser.screen_name"
								,"FollowingUser.avatar"),
						'order' => array('id' => 'asc')
				));
				$followers = $this->checkFollowerStatus($current, $followers);
				$data = array("status_code" => 0 , "message" => "","entity" => $followers);
				echo json_encode($data) ;
			}else{
				$start = $this->numberPerPage * ($this->request->data["paging"]-1);

				$this->Follow->unbindModel(array("belongsTo" => array("FollowerUser")));

				$followers = $this->Follow->find("all" , array("conditions" => array("following_id" => $userid),
						"fields" => array("FollowingUser.id","FollowingUser.username","FollowingUser.email","FollowingUser.screen_name"
								,"FollowingUser.avatar"),
						'order' => array('id' => 'asc'), "limit" => $this->numberPerPage, "offset" =>$start));
				$followers = $this->checkFollowerStatus($current, $followers);
				$data = array("status_code" => 0 , "message" => "","entity" => $followers);
				echo json_encode($data) ;
			}
		}else{
			$this->autoRender = true;
		}
	}

	private  function checkFollowerStatus($userid,$followers){
		$followings = $this->Follow->find("all" , array("conditions" => array("follower_id" => $userid),
				"fields" => array("Follow.following_id"),"recursive"=>-1,"order" => array('id' => 'asc')));

		for($i = 0;$i < count($followers);$i++){
			for($j = 0;$j < count($followings) ; $j++){
				if($followers[$i]["FollowingUser"]["id"] == $followings[$j]["Follow"]["following_id"]){
					$followers[$i]["FollowingUser"]["followStatus"] = true;
					break;
				}
			}
			if(!isset($followers[$i]["FollowingUser"]["followStatus"])){
				$followers[$i]["FollowingUser"]["followStatus"] = false;
			}
		}
		return  $followers;
	}

	private  function checkFollowingStatus($userid,$followings){
		$followers = $this->Follow->find("all" , array("conditions" => array("follower_id" => $userid),
				"fields" => array("Follow.following_id"),"recursive"=>-1,"order" => array('id' => 'asc')));

		for($i = 0;$i < count($followings);$i++){
			for($j = 0;$j < count($followers) ; $j++){
				if($followings[$i]["FollowerUser"]["id"] == $followers[$j]["Follow"]["following_id"]){
					$followings[$i]["FollowerUser"]["followStatus"] = true;
					break;
				}
			}
			if(!isset($followings[$i]["FollowerUser"]["followStatus"])){
				$followings[$i]["FollowerUser"]["followStatus"] = false;
			}
		}
		return  $followings;
	}


	/**
	 * list all user that this user is following
	 * @userid id of user want to get follower
	 * @accesstoken token of current logged in user
	 */
	public function followings(){
		if($this->request->is("post")){
			$this->autoRender = false;
			if(empty($this->request->data["get_userid"])){
				$data = array("status_code" => -1 , "message" => "access denied","entity" => array());
				return json_encode($data);
			}else{
				$userid = $this->request->data["get_userid"];
			}
				
			$current = $this->request->data["userid"];
				
			$this->Follow->unbindModel(array("belongsTo" => array("FollowingUser")));

			if(empty($this->request->data["paging"])){
				$followings = $this->Follow->find("all" , array("conditions" => array("follower_id" => $userid),
						"fields" => array("FollowerUser.id","FollowerUser.username","FollowerUser.email"
								,"FollowerUser.screen_name","FollowerUser.avatar")));
				$followings = $this->checkFollowingStatus($current, $followings);
				$data = array("status_code" => 0 , "message" => "","entity" => $followings);
				//debug($followings);
				echo json_encode($data);
			}else{
				$start = $this->numberPerPage * ($this->request->data["paging"]-1);
				$followings = $this->Follow->find("all" , array("conditions" => array("follower_id" => $userid),
						"fields" => array("FollowerUser.id","FollowerUser.username","FollowerUser.email"
								,"FollowerUser.screen_name","FollowerUser.avatar"),
						'order' => array('id' => 'asc'), "limit" => $this->numberPerPage, "offset" =>$start));
				$followings = $this->checkFollowingStatus($current, $followings);
				$data = array("status_code" => 0 , "message" => "","entity" => $followings);
				//debug($followings);
				echo json_encode($data);
			}
		}else{
			$this->autoRender = true;
		}

	}

	/**
	 * follow 2 user
	 * @userid id of follower
	 * @followed id of followed user
	 */
	public function follow(){
		$this->autoRender = false;
		if($this->request->is("post")){
			$this->autoRender = false;
			if(empty( $this->request->data['followedId']) || empty( $this->request->data["userid"])){
				$data = array("status_code" => -1 , "message" => "access denied","entity" => array());
				return json_encode($data);
			}else{
				$followedId = $this->request->data['followedId'];
				$userId = $this->request->data['userid'];
			}

			// check if they already followed
			$alreadyResult = $this->Follow->find("first", array("conditions" =>
					array("follower_id" => $userId,"following_id" => $followedId),"recursive" => -1) );
			if($alreadyResult){
				// when they already follow,show error message
				$data = array("status_code" => -1 , "message" => "Follow faile","entity" => array());
				return json_encode($data);
			}

			// Chuyen du lieu nguoi dung tu bang tweets sang bang timeline
			$allUserTweeted = $this->Tweet->find("all",
					array("conditions"=>array("user_id"=>$followedId),"recursive" => -1,
							"fields" => array("id")));
			$allTimelines=array();
			foreach ($allUserTweeted as $tweet){
				$timeline = array("user_id" => $userId,"followed_id" => $followedId,"tweet_id"=>$tweet["Tweet"]["id"]);
				array_push($allTimelines, $timeline);
			}
				
			if(count($allTimelines) > 0){
				$this->Timeline->saveMany($allTimelines);
			}
			// Them thong tin follow vao bang follow

			$this->Follow->create();  
			$data = array("follower_id" => $userId,"following_id" => $followedId);
			$this->Follow->set($data);
			$this->Follow->save();
			
			$followedUser = $this->User->find("first", array("conditions" =>
					array("id" => $followedId),"recursive" => -1) );
			$followUser = $this->User->find("first", array("conditions" =>
					array("id" => $userId),"recursive" => -1) );
			// check if they already followed
			$alreadyResult2 = $this->Follow->find("first", array("conditions" =>
					array("follower_id" => $followedId,"following_id" => $userId),"recursive" => -1) );
			if($alreadyResult2){
				$followUser["User"]["followStatus"] = true;
			}
			
				
			$this->pushnofifycation($followUser["User"], $followedUser["User"]);

			//debug($this->Follow->find("all",array("conditions" => array("follower_id" => $userId),"recursive" => -1)));
			$data = array("status_code" => 0 , "message" => "Follow success","entity" => array());
			return json_encode($data);
		}
	}

	/**
	 * unfollow 2 followed user
	 * @userid id of user want to unfollow
	 * @followedid is user of user that user above want to unfollow
	 */
	public function unfollow(){
		$this->autoRender = true;
		if($this->request->is("post")){
			$this->autoRender = false;
			if(empty( $this->request->data['followedId']) || empty( $this->request->data["userid"])){
				$data = array("status_code" => -1 , "message" => "access denied","entity" => array());
				return json_encode($data);
			}else{
				$followedId = $this->request->data['followedId'];
				$userId = $this->request->data['userid'];
			}

			// check if they already followed
			$alreadyResult = $this->Follow->find("first", array("conditions" =>
					array("follower_id" => $userId,"following_id" => $followedId),"recursive" => -1) );
			if(!$alreadyResult){
				// when they already follow,show error message
				$data = array("status_code" => -1 , "message" => "Unfollow faile","entity" => array());
				return json_encode($data);
			}

			// delete all tweets of this users in timeline
			$this->Timeline->deleteAll(array("Timeline.user_id" => $userId,"Timeline.followed_id" => $followedId),false);
				
			$query = "delete   Tweet from tweets as Tweet
			inner join tweets as Tweet1
			on Tweet.type = 3 and Tweet.user_id = $userId and Tweet.parent_id = Tweet1.id and Tweet1.user_id = $followedId";
			
			$this->Tweet->getDataSource()->query($query);
			
			// Xoa thong tin follow trong bang follow
			$this->Follow->deleteAll(array("Follow.follower_id" => $userId,"Follow.following_id" => $followedId),false);

			$data = array("status_code" => 0 , "message" => "Unfollow success","entity" => array());
			return json_encode($data);
		}
	}
	
	private function pushnofifycation($user,$followed){
		$url = 'https://android.googleapis.com/gcm/send';
		$serverApiKey = "AIzaSyAmubg2LaSEzHQmKhYcboKKBzYX9J1rtGM";
		$reg =$followed['reg_id'];
	
		$headers = array(
				'Content-Type:application/json',
				'Authorization:key=' . $serverApiKey
		);
		$datas = array($user,$followed);
		$data = array(
				'registration_ids' => array($reg)
				, 'data' => array(
						'type' => 'News follow!!',
						'title' => 'FakeTwitter',
						'msg' =>json_encode($datas),
						'url' => 'http://faketwitter.com',
				)
		);
	
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		if ($headers)
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
	
		$response = curl_exec($ch);
	
		curl_close($ch);
	}

	public function tfl(){
		$this->autoRender = true;
	}

	public function tufl(){
		$this->autoRender = true;
	}

}